<template>
  <base-page-container activeTab="camera">
    <template #header>
      <!-- 页面头部 -->
      <view class="header">
        <u-status-bar></u-status-bar>
        <view class="header-content">
          <view class="header-left">
            <text class="header-title">中药识别</text>
            <text class="header-desc">快速识别中药材，专业辨别功效</text>
          </view>
        </view>
      </view>
    </template>
    <template #content>
      <view class="container">
        <view class="guide-section">
          <view class="guide-content">
            <image
              class="guide-avatar"
              src="https://ai-public.mastergo.com/ai/img_res/cc900c00d9fd76ec56595c59a88ffeb2.jpg" />
            <view class="guide-text">
              <text>Hi，我来教你使用~</text>
              <text>1. 点击下方按钮拍照或上传图片</text>
              <text>2. 等待识别结果</text>
              <text>3. 查看详细信息</text>
            </view>
          </view>
        </view>
        <!-- 操作按钮区 -->
        <view class="action-section">
          <view class="action-btn" @click="handleTakePhoto">
            <up-icon name="camera-fill" size="28" color="#FFFFFF" />
            <text>拍照</text>
          </view>
          <view class="action-btn" @click="handleUpload">
            <up-icon name="photo-fill" size="28" color="#FFFFFF" />
            <text>上传</text>
          </view>
        </view>
        <!-- 预览区 -->
        <view v-if="previewImage" class="preview-section">
          <view class="preview-header">
            <text class="preview-title">图片预览</text>
            <up-icon
              name="close"
              size="24"
              color="#666666"
              @click="clearPreview" />
          </view>
          <image :src="previewImage" mode="aspectFit" class="preview-image" />
          <view class="preview-actions">
            <view class="confirm-btn" type="primary" @click="handleConfirm">
              确认识别
            </view>
            <view class="retry-btn" @click="clearPreview">重新识别</view>
          </view>
        </view>
        <!-- 相关推荐区 -->
        <base-card-container title="药膳套餐推荐" @more="toList">
          <template #content>
            <scroll-view
              v-if="recommendList?.length > 0"
              class="recommend-list"
              scroll-x="true">
              <view
                class="recommend-item"
                v-for="(item, index) in recommendList"
                :key="index">
                <image
                  :src="viewImg(item.image)"
                  mode="aspectFill"
                  class="recommend-image" />
                <text class="recommend-name">{{ item.name }}</text>
                <view class="recommend-bottom">
                  <text class="recommend-price">{{ item.price }}</text>
                  <view class="buy-btn" @click="handleBuy(item.id)">购买</view>
                </view>
              </view>
            </scroll-view>
            <up-empty
              v-else
              text="暂无相关推荐"
              icon="http://www.adnaan.cn/chinese-images/empty.png"></up-empty>
          </template>
        </base-card-container>
      </view>
    </template>
  </base-page-container>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { getHotProduct_api, saveIdentifyHerb_api } from "@/api/api";
import { upload } from "@/api/upload";
import { ALGORITHM_URL } from "@/api/constant";
import { viewImg } from "@/utils/image";

const previewImage = ref("");

const recognizeType = ref(0);

const saveRecord = async (result, url, status) => {
  const params = {
    image: url,
    result: result.id,
    status: status,
    type: recognizeType.value,
  };
  await saveIdentifyHerb_api(params);
};

const handleConfirm = async () => {
  // 检查是否有预览图片
  if (!previewImage.value) {
    uni.showToast({
      title: "请先选择图片",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 显示加载提示
  uni.showToast({
    title: "开始识别...",
    icon: "loading",
    duration: 2000,
  });

  const res = await upload("file", previewImage.value);
  const { data } = JSON.parse(res);
  const url = data.url;

  // 上传图片到算法服务器
  uni.uploadFile({
    url: ALGORITHM_URL,
    filePath: previewImage.value,
    name: "image",
    success: (uploadRes) => {
      // 处理上传成功后的逻辑
      const result = JSON.parse(uploadRes.data);
      // 如果置信度小于等于0.4直接识别失败
      console.log("识别结果", result);
      if (result.confidence > 0.2) {
        // 显示加载提示
        uni.showLoading({
          title: "识别成功...",
          mask: true, // 防止用户点击
        });
        saveRecord(result, url, 1);
        // 延迟跳转，确保用户看到提示
        setTimeout(() => {
          uni.navigateTo({
            url: `/subPackages/result/detail?id=${result.id}&confidence=${result.confidence}`,
            success: () => {
              uni.hideLoading(); // 跳转成功后关闭 loading
            },
            fail: (err) => {
              uni.hideLoading(); // 跳转失败后关闭 loading
              uni.showToast({
                title: "跳转失败",
                icon: "none",
                duration: 2000,
              });
              console.error("跳转失败:", err);
            },
          });
        }, 1500); // 延迟 1.5 秒跳转
      } else {
        uni.showToast({
          title: "识别失败",
          icon: "none",
          duration: 2000,
        });
        saveRecord(result, url, 0);
      }
    },
    fail: (err) => {
      // 处理上传失败
      uni.showToast({
        title: "上传失败",
        icon: "none",
        duration: 2000,
      });
      console.error("上传失败:", err);
    },
  });
};
const handleTakePhoto = () => {
  recognizeType.value = 0;
  uni.chooseImage({
    count: 1,
    sourceType: ["camera"],
    success: (res) => {
      previewImage.value = res.tempFilePaths[0];
    },
  });
};
const handleUpload = () => {
  recognizeType.value = 1;
  uni.chooseImage({
    count: 1,
    sourceType: ["album"],
    success: (res) => {
      previewImage.value = res.tempFilePaths[0];
    },
  });
};
const clearPreview = () => {
  previewImage.value = "";
};

//商品
const recommendList = ref([]);
const toList = () => {
  uni.navigateTo({
    url: "/subPackages/goods/list",
  });
};
const handleBuy = (id) => {
  uni.navigateTo({
    url: "/subPackages/goods/detail?id=" + id,
  });
};
const getHotGoods = async () => {
  const res = await getHotProduct_api();
  const { data } = res;
  recommendList.value = data;
  recommendList.value.forEach((item) => {
    item.image = JSON.parse(item.cover)[0]?.data;
  });
};
onLoad(() => {
  getHotGoods();
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100%;
  padding: 30rpx;
  box-sizing: border-box;
}
.guide-section {
  margin-bottom: 40rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
}
.guide-content {
  display: flex;
  align-items: flex-start;
}
.guide-avatar {
  width: 200rpx;
  height: 200rpx;
  margin-right: 30rpx;
  flex-shrink: 0;
}
.guide-text {
  flex: 1;
}
.header {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  background: linear-gradient(
    135deg,
    $color-primary-dark 0%,
    $color-primary-light 100%
  );
  backdrop-filter: blur(20rpx);
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  margin-bottom: 40rpx;
  border-radius: 60rpx;
  box-shadow: 0 4rpx 20rpx rgba(74, 144, 226, 0.1);
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}
.header-left {
  flex: 1;
}
.header-title {
  display: block;
  font-size: 28px;
  color: #ffffff;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.header-desc {
  display: block;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}
.guide-text text {
  display: block;
  font-size: 14px;
  color: #666666;
  line-height: 1.6;
  margin-bottom: 10rpx;
}
.action-section {
  display: flex;
  justify-content: center;
  gap: 40rpx;
  margin-bottom: 40rpx;
}
.action-btn {
  width: 320rpx;
  height: 160rpx;
  background-color: $color-primary-light;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 20rpx;
}
.action-btn text {
  color: #ffffff;
  font-size: 28rpx;
  margin-top: 10rpx;
}
.preview-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
}
.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.preview-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}
.preview-image {
  width: 100%;
  height: 400rpx;
  border-radius: 8rpx;
}
.preview-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 30rpx;
}
.confirm-btn {
  flex: 1;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #4a90e2;
  color: #ffffff;
  border-radius: 8rpx;
}
.retry-btn {
  flex: 1;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  color: #666666;
  border-radius: 8rpx;
}
.result-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
}
.result-header {
  margin-bottom: 20rpx;
}
.result-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
}
.result-name {
  font-size: 20px;
  color: #4a90e2;
  font-weight: bold;
  display: block;
}
.result-detail {
  border-top: 1px solid #eeeeee;
  padding-top: 20rpx;
}
.detail-item {
  display: flex;
  margin-bottom: 16rpx;
}
.detail-label {
  width: 160rpx;
  color: #999999;
  font-size: 14px;
}
.detail-value {
  flex: 1;
  color: #333333;
  font-size: 14px;
}
.recommend-list {
  white-space: nowrap;
  padding: 20rpx;
  box-sizing: border-box;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  &::-webkit-scrollbar {
    display: none;
  }
}
.recommend-item {
  display: inline-block;
  margin: 30rpx 20rpx;
  width: 300rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 15rpx 35rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  &:hover {
    transform: translateY(-6rpx);
    box-shadow: 0 20rpx 45rpx rgba(0, 0, 0, 0.15);
  }
  &:last-child {
    margin-right: 0;
  }
}
.recommend-image {
  width: 100%;
  height: 260rpx;
  border-radius: 12rpx;
  margin-bottom: 16rpx;
}
.recommend-name {
  font-size: 28rpx;
  color: #333333;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 16rpx;
  font-weight: 600;
}
.recommend-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.recommend-price {
  color: #ff4757;
  font-size: 32rpx;
  font-weight: bold;
  &::before {
    content: "¥";
    font-size: 24rpx;
    margin-right: 4rpx;
  }
}
.buy-btn {
  padding: 0 28rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: linear-gradient(135deg, #3acf7b 0%, #2ecc71 100%);
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  font-weight: 500;
  transition: all 0.3s ease;
  &:active {
    transform: scale(0.95);
    opacity: 0.9;
  }
}
.recommend-item:active {
  transform: scale(0.98);
}
</style>
